package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberAddressVo;
import com.atguigu.common.vo.MemberVo;
import com.atguigu.gulimall.order.constant.Orderconstan;
import com.atguigu.gulimall.order.feign.CartFeign;
import com.atguigu.gulimall.order.feign.MemberFeign;
import com.atguigu.gulimall.order.feign.WareFeign;
import com.atguigu.gulimall.order.interceptro.OrderLoginInterceptro;
import com.atguigu.gulimall.order.service.OrderWebService;
import com.atguigu.gulimall.order.vo.ConfirmVo;
import com.atguigu.gulimall.order.vo.OrderItemVo;
import com.atguigu.gulimall.order.vo.WarehasStockVo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderWebServerImpl implements OrderWebService{

    @Autowired
    MemberFeign memberFeign;

    @Autowired
    CartFeign cartFeign;

    @Autowired
    WareFeign wareFeign;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 结算页信息
     * @return
     */
    @SneakyThrows
    @Override
    public ConfirmVo getToRrade() {
        ConfirmVo confirmVo = new ConfirmVo();
        //获取用户信息
        MemberVo memberVo = OrderLoginInterceptro.threadLocal.get();
        //线程共享 获取
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> member = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //根据用户id获取地址信息 远程调用
            List<MemberAddressVo> address = memberFeign.getAddress(memberVo.getId());
            confirmVo.setVos(address);
        }, executor);

        /**
         * executor：使用此线程池
         * thenRunAsync：上边的异步执行完成之后执行该任务
         */
        CompletableFuture<Void> cart = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //获取用户购物车商品信息 远程调用
            List<OrderItemVo> cartOrder = cartFeign.getCartOrder();
            confirmVo.setItemVos(cartOrder);

        }, executor).thenRunAsync(()-> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
                    //查询库存信息
                    List<OrderItemVo> itemVos = confirmVo.getItemVos();
                    //获取skuId
            List<Long> longs = itemVos.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R skuStock = wareFeign.findSkuStock(longs);
            List<WarehasStockVo> data = skuStock.getData(new TypeReference<List<WarehasStockVo>>() {
            });
            if (data!=null){
                Map<Long, Boolean> collect = data.stream().collect(Collectors.toMap(WarehasStockVo::getSkuId, WarehasStockVo::getHasStock));
                confirmVo.setStocks(collect);
            }
        },executor);
        //查询用户积分
        //Integer integration = memberVo.getIntegration();

        //防重令牌 防止重复提交
        String replace = UUID.randomUUID().toString().replace("_", "");
        redisTemplate.opsForValue().set(Orderconstan.ORDER_TOKEN_PREFIX+ memberVo.getId(),replace,30, TimeUnit.MINUTES);
        confirmVo.setToken(replace);


        CompletableFuture.allOf(member, cart).get();
        return confirmVo;
    }
}
